package com.school.controller;

import com.school.entity.Attendance;
import com.school.entity.ClassEntity;
import com.school.entity.Student;
import com.school.service.AttendanceService;
import com.school.service.ClassService;
import com.school.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/attendance")
public class AttendanceController {
    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private ClassService classService;

    @GetMapping("/list")
    public List<Map<String, Object>> list(@RequestParam(required = false) Long classId,
                                 @RequestParam(required = false) String date,
                                 @RequestParam(required = false) String studentId) {
        List<Attendance> attendances;

        if (classId != null && date != null) {
            attendances = attendanceService.findByClassIdAndDate(classId, LocalDate.parse(date));
        } else if (classId != null) {
            attendances = attendanceService.findByClassId(classId);
        } else if (studentId != null) {
            attendances = attendanceService.findByStudentId(studentId);
        } else if (date != null) {
            attendances = attendanceService.findByDate(LocalDate.parse(date));
        } else {
            attendances = attendanceService.findAll();
        }

        // 获取所有班级信息，用于转换班级ID为班级名称
        Map<Long, String> classMap = classService.findAll().stream()
                .collect(Collectors.toMap(ClassEntity::getId, ClassEntity::getName));

        // 获取所有学生信息，用于添加学生姓名
        Map<String, Student> studentMap = studentService.findAll().stream()
                .collect(Collectors.toMap(Student::getStudentId, student -> student));

        // 转换为前端需要的格式，添加学生姓名和班级名称
        return attendances.stream().map(attendance -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", attendance.getId());
            map.put("studentId", attendance.getStudentId());
            map.put("date", attendance.getDate());
            map.put("status", attendance.getStatus());
            map.put("remark", attendance.getRemark());
            map.put("classId", attendance.getClassId());

            // 添加学生姓名
            Student student = studentMap.get(attendance.getStudentId());
            if (student != null) {
                map.put("studentName", student.getName());
                // 如果考勤记录没有班级ID，使用学生的班级ID
                if (attendance.getClassId() == null && student.getClassId() != null) {
                    map.put("classId", student.getClassId());
                    map.put("className", classMap.getOrDefault(student.getClassId(), ""));
                } else {
                    map.put("className", classMap.getOrDefault(attendance.getClassId(), ""));
                }
            } else {
                map.put("studentName", "未知学生");
                map.put("className", classMap.getOrDefault(attendance.getClassId(), ""));
            }

            return map;
        }).collect(Collectors.toList());
    }

    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Attendance attendance) {
        Map<String, Object> result = new HashMap<>();

        // 检查学生是否存在
        if (studentService.findByStudentId(attendance.getStudentId()).isEmpty()) {
            result.put("success", false);
            result.put("message", "学生不存在");
            return result;
        }

        // 保存考勤记录
        Attendance saved = attendanceService.save(attendance);

        result.put("success", true);
        result.put("data", saved);
        return result;
    }

    @PostMapping("/edit")
    public Map<String, Object> edit(@RequestBody Attendance attendance) {
        Map<String, Object> result = new HashMap<>();
        Optional<Attendance> exist = attendanceService.findById(attendance.getId());
        if (exist.isEmpty()) {
            result.put("success", false);
            result.put("message", "考勤记录不存在");
            return result;
        }
        Attendance att = exist.get();
        att.setStatus(attendance.getStatus());
        att.setRemark(attendance.getRemark());
        att.setDate(attendance.getDate());
        att.setClassId(attendance.getClassId());
        att.setStudentId(attendance.getStudentId());
        attendanceService.save(att);
        result.put("success", true);
        return result;
    }

    @PostMapping("/delete")
    public Map<String, Object> delete(@RequestBody Map<String, Long> param) {
        Map<String, Object> result = new HashMap<>();
        Long id = param.get("id");
        if (id == null || attendanceService.findById(id).isEmpty()) {
            result.put("success", false);
            result.put("message", "考勤记录不存在");
            return result;
        }
        attendanceService.deleteById(id);
        result.put("success", true);
        return result;
    }

    @PostMapping("/batch")
    public Map<String, Object> batch(@RequestBody List<Attendance> list) {
        Map<String, Object> result = new HashMap<>();

        // 检查每个考勤记录的学生是否存在
        for (Attendance attendance : list) {
            if (studentService.findByStudentId(attendance.getStudentId()).isEmpty()) {
                result.put("success", false);
                result.put("message", "学生ID " + attendance.getStudentId() + " 不存在");
                return result;
            }
        }

        // 保存所有考勤记录
        attendanceService.saveAll(list);

        result.put("success", true);
        return result;
    }
}
